package com.recsmile.rpc.consumer.net;

import com.recsmile.rpc.bo.RpcMessageRequest;
import com.recsmile.rpc.bo.RpcMessageResponse;
import io.netty.channel.ChannelHandlerContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/11.
 */
public class RpcMessageRecvHandlerTask implements Runnable{

    private RpcMessageRequest request;
    private ChannelHandlerContext ctx;
    private Map<String, Object> serviceMap;

    public RpcMessageRecvHandlerTask(RpcMessageRequest request, ChannelHandlerContext ctx, Map<String, Object> serviceMap) {
        this.request = request;
        this.ctx = ctx;
        this.serviceMap = serviceMap;
    }

    public void run() {

        RpcMessageResponse response = new RpcMessageResponse();
        response.setMessageId(request.getMessageId());
        try{
            response.setResult(reflect(request));
        }catch (Exception e){
            response.setErrMsg(e.toString());
        }
        ctx.writeAndFlush(response);

        //System.out.println("recv:"+ response.getMessageId());
    }

    private Object reflect(RpcMessageRequest request) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Object serviceBean = serviceMap.get(request.getClassName());
        if(serviceBean == null){
            throw  new RuntimeException();
        }
        Method method = serviceBean.getClass().getMethod(request.getMethodName(), request.getPerameterTypes());
        return method.invoke(serviceBean, request.getArgs());
    }
}
